<template>
  <div ref="charts" class="charts" />
</template>

<script>
import * as echarts from "echarts";
import { mapGetters, mapState } from "vuex";

export default {
  name: "BarCharts",
  data() {
    return {
      mycharts: null,
    };
  },
  computed: {
    ...mapGetters("classL", ["classCount"]),
    ...mapState("classL", ["classList"]),
    classNameList() {
      return this.classList.map((item) => item.name);
    },
  },
  watch: {
    // 监听classCount的变化，当classCount发生变化的时候，重新渲染图表
    classCount() {
      this.$nextTick(() => {
        this.initEcharts();
      });
    },
  },
  mounted() {
    // 初始化图表
    this.mycharts = echarts.init(this.$refs.charts);
    // 初次渲染图表
    this.initEcharts();
    // 当浏览器发生resize事件的时候，让其触发echarts的resize事件，重绘canvas
    window.addEventListener("resize", () => {
      this.mycharts.resize();
    });
    // 图表的点击事件
    this.mycharts.on("click", (params) => {
      this.$router.push({
        name: "StudentList",
        query: {
          name: params.name,
          type: 1,
        },
      });
    });
  },
  methods: {
    initEcharts() {
      // 初始化charts实例
      this.mycharts.setOption({
        // x轴
        xAxis: {
          show: false,
          type: "category",
          data: this.classNameList,
        },
        // y轴
        yAxis: {
          show: false,
        },
        // 系列
        series: [
          {
            type: "bar", // 柱状图
            data: this.classCount,
            showBackground: true,
            barWidth: 30,
            backgroundStyle: {
              color: "#eaf0f8",
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                0,
                1,
                0,
                0,
                [
                  {
                    offset: 0,
                    color: "rgb(88, 108, 177)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(61, 151, 221, 0.5)", // 100% 处的颜色
                  },
                ],
                false
              ),
            },
          },
        ],
        tooltip: {
          trigger: "item",
          formatter: "{b}：{c}人",
        },
        grid: {
          left: "0%",
          top: "0%",
          right: "0%",
          bottom: "0%",
        },
      });
    },
  },
};
</script>

<style scoped>
.charts {
  width: 100%;
  height: 100%;
}
</style>
